// pages/video/video.js
import request from '../../utils/request'
let timer
Page({

  /**
   * 页面的初始数据
   */
  data: {
    videoTagList: [],
    selectedId: '',
    videoList: [],
    videoId: '',
    videoUpdateTime: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getVideoTagList()
  },
  // 获取视频标签
  async getVideoTagList() {
    const res = await request('/video/group/list')
    console.log('getVideoTagList-res--', res);
    const data = res.data.slice(0, 14)
    this.setData({
      videoTagList: data,
      selectedId: data[0].id
    }, () => {
      this.getVideoList()
    })
  },
  // 点击视频标签
  selectNav(e) {
    this.setData({
      selectedId: e.target.dataset.id
    }, () => {
      this.getVideoList()
    })
  },
  // 获取视频
  async getVideoList() {
    wx.showLoading({
      title: '加载中'
    })
    this.setData({
      videoList: []
    })
    const res = await request('/video/group', {id: this.data.selectedId})
    console.log('getVideoList-res---', res);
    let index = 0
    const data = res.datas.map(item => {
      item.id = index++
      return item
    })
    this.setData({
      videoList: data
    }, () => {
      wx.hideLoading()
    })
  },
  // 点击开始/继续播放视频的回调
  handlePlay(e) {
    // this.vid != e.target.id && this.currentVideo?.stop()
    // this.vid = e.target.id
    const vid = e.target.id
    this.setData({
      videoId: vid
    })
    this.currentVideo = wx.createVideoContext(vid)
    this.data.videoUpdateTime[e.target.id] && this.currentVideo.seek(this.data.videoUpdateTime[e.target.id])
    this.currentVideo.play()
  },
  // 播放进度变化时
  handleUpdateTime(e) {
    console.log(e.target.id);
    console.log(e.detail);
    timer && clearTimeout(timer)
    timer = setTimeout(() => {
      const obj = {
        id: e.target.id,
        currentTime: e.detail.currentTime
      }
      const temp = Object.assign({}, this.data.videoUpdateTime)
      temp[e.target.id] = e.detail.currentTime
      this.setData({
        videoUpdateTime: temp
      })
    }, 300)
  },
  // 播放结束
  handleEnd(e) {
    const temp = Object.assign({}, this.data.videoUpdateTime)
    delete temp[e.target.id]
    setTimeout(() => {
      this.setData({
        videoUpdateTime: temp
      })
    }, 500)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})